package com.bsoft.exchange.service;

import com.bsoft.EmrBLService.DataToHtml;
import com.bsoft.EmrBLService.FileUtil;
import com.bsoft.exchange.dao.emr.RecordMapper;
import com.bsoft.exchange.dao.emr.TemplateMapper;
import com.bsoft.exchange.dao.his.ClinicMedicationMapper;
import com.bsoft.exchange.dao.omr.ClinicRecordMapper;
import com.bsoft.exchange.dao.portal.HospitalInformationMapper;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.CostAggregationPojo;
import com.bsoft.exchange.pojo.HealthRecordsPojo;
import com.bsoft.exchange.pojo.MedicalRecordIdPojo;
import com.bsoft.exchange.pojo.OrganizationIdPojo;
import com.bsoft.exchange.util.BaseResponse;
import com.bsoft.exchange.util.CacheSupport;
import com.bsoft.exchange.util.Constant;
import com.bsoft.exchange.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RecordService {
	
	public static final String FormatStr ="yyyy-MM-dd";
	
	@Autowired
	ClinicMedicationMapper clinicMedicationMapper;

	@Autowired
	TemplateMapper templateMapper;
	
	@Autowired
	RecordMapper recordMapper;

	@Autowired
	PublicService publicService;

	@Autowired
	CacheSupport cacheSupport;
	@Autowired
	ClinicRecordMapper clinicRecordMapper;

	@Autowired
	HospitalInformationMapper hospitalInformationMapper;
	private List<HealthRecordsDomain> mzHealthRecords;
	private List<HealthRecordsDomain> healthRecordsList;
	private List<HealthRecordsDomain> zyHealthRecords;

	public BaseResponse<List<AdmissionNoteDomain>> admissionNote(CostAggregationPojo  costAggregationPojo,
																 HttpServletRequest request){
		
		BaseResponse<List<AdmissionNoteDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Long jgid;
			 String jzhm ;
	         if(costAggregationPojo.getOrganizationId() == null || "".equals(costAggregationPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;
	         }
	           
	        jgid = Long.parseLong(costAggregationPojo.getOrganizationId());
			
	        if(costAggregationPojo.getInHospitalRecordNumber() == null || "".equals(costAggregationPojo.getInHospitalRecordNumber())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("住院号不能为空!");
	        	  
	             return response;
	         }
	        jzhm = costAggregationPojo.getInHospitalRecordNumber();
	        
	        //获取所有病历 + 第一份病程即可
	        List<AdmissionNoteDomain> admissionNoteList = recordMapper.getPatientEmrRecordList(jzhm);
	        for(AdmissionNoteDomain admissionNote : admissionNoteList){
	        	
	        	 Map<String,Object> result = getUrlByRecordId(Long.parseLong(admissionNote.getMedicalRecordId()),1L,2L);
				 if(Long.parseLong(result.get("result").toString()) == 1){

					 admissionNote.setWebAddress(request.getScheme() + "://"
							 + request.getServerName() +":"+ request.getServerPort()+ "/temp/doc/"+result.get("filePathName").toString());
				 }else{
					
				 }
	        }
			
	        response.setData(admissionNoteList);
			response.setMessage("处理成功");
	        
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
public BaseResponse<List<SyncTemplateDomain>> syncTemplate(OrganizationIdPojo  organizationIdPojo){
		
		BaseResponse<List<SyncTemplateDomain>> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 /*Long jgid;

	         if(organizationIdPojo.getOrganizationId() == null || "".equals(organizationIdPojo.getOrganizationId())){
	        	 response.setCode(Constant.errorTag);
	        	 response.setMessage("医院识别代码不能为空!");
	        	  
	             return response;
	         }
	           
	        jgid = Long.parseLong(organizationIdPojo.getOrganizationId());*/
			
			List<SyncTemplateDomain> bllbList = recordMapper.getEmrBllbList();
	
			if(bllbList == null ||bllbList.size() < 1){
	        	response.setMessage("未查询到数据！");
	        }else{
	        	
	        	for(SyncTemplateDomain bllb:bllbList){
	        		
	        		List<TemplateClassDomain> mblbList = recordMapper.getEmrMblbList(Long.parseLong(bllb.getMedicalClassId()));
	        		bllb.setTemplateClassList(mblbList);
	        	}
	        	
	        	response.setMessage("处理成功");
				response.setData(bllbList);
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	
	/**
	 * 获取病历html文件地址。
	 * @return
	 */
	public BaseResponse<String> getRecordUrl(MedicalRecordIdPojo medicalRecordIdPojo){
		
		BaseResponse<String> response = new BaseResponse<>();
		response.setCode(Constant.successResponse);
		response.setData(null);
		try {
			
			 Map<String,Object> result = getUrlByRecordId(Long.parseLong(medicalRecordIdPojo.getMedicalRecordId()),1L,2L);
			 if(Long.parseLong(result.get("result").toString()) == 1){
				 response.setData(result.get("url").toString());
				 response.setMessage("处理成功");
			 }else{
				response.setCode(Constant.errorTag);
				response.setMessage("处理失败"+result.get("errorText").toString());
			 }
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setCode(Constant.errorTag);
			response.setMessage("处理失败"+e.getMessage());
		}
		
		
		return response;
	}
	
	
	/**
	 * 根据病历编号获取htm的URL recordType ,
	 * 参照病历解析里的html展示
	 * @param recordId  病历id
	 * @param type      0 单病历展示 1合并展示 主要针对病程
	 * @param outInSign 门诊住院标志 1门诊 2 住院
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws MalformedURLException 
	 */
	public Map<String, Object> getUrlByRecordId(Long recordId,Long type ,Long outInSign) throws UnsupportedEncodingException, MalformedURLException {
		Map<String, Object> result = new HashMap<String, Object>();

		// 设置存储位置
		String localPath = this.getClass().getClassLoader().getResource("").getPath();
		try {
			localPath = URLDecoder.decode(localPath, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			result.put("result", 0);
			result.put("errorText", "转UTF-8编码失败!");
			return result;
		}
		//门诊住院 病历路径 doc  doc/clinicdoc
		String docPath ="";
		if("1".equals(outInSign.toString())){
			docPath +="clinicdoc/";
		}

		if (localPath.indexOf("target") >= 0) {
			localPath = localPath.replace("target/classes/", "src/main/webapp/doc/"+docPath);
			localPath = localPath.replace("target/test-classes/", "src/main/webapp/doc/"+docPath);
		} else {
			//localPath = localPath.replace("WEB-INF/classes/", "doc/"+docPath);
			//E:\SoftWare\tomcat\webapps\framework\WEB-INF\classes
			int index = localPath.indexOf("webapps");
			if ( index >= 0) {
				localPath = localPath.substring(0,index) + "temp/doc/"+docPath;
			}
		}

		localPath = localPath.substring(1);

		// 查询病历数据
		RecordDomain record = new RecordDomain();
		if("1".equals(outInSign.toString())){
			// 查询门诊病历数据  跨库，分两次查询
			record = clinicMedicationMapper.getClinicRecordById(recordId);
			RecordDomain record2 = clinicRecordMapper.getClinicRecordDataById(recordId);
			if (record == null || record2 == null) {
				result.put("result", 0);
				result.put("errorText", "未查询到病历内容!");
				return result;
			}

			record.setBlnr(record2.getBlnr());
		}else{
			record = recordMapper.getEmrRecordById(recordId);
			if (record == null) {
				result.put("result", 0);
				result.put("errorText", "未查询到病历内容!");
				return result;
			}
		}

		// 3种类型不同处理   --文档路径规则 jzhm / bllb /blbh.html
		// 1.病历:获取内容 通过转换服务转
		// 2.病历:获取所有病程内容 通过转换服务转
		// 3.病案首页:获取内容写html文件

		String filePath = record.getVisitId()+"/"+record.getRecordTypeCode() + "/" ;
		String fileName = "" + record.getRecordId() + ".html";
		String data = new String(record.getBlnr(),"gbk");
		String realPath = localPath + filePath + fileName;
		//URL url = new File(realPath).toURI().toURL();
		if(type == 0){
			record.setType(0);
		}
		
		if (record.getRecordType() == 1) {
			// ===================================================================
			// 病案首页
			// ===================================================================
			FileUtil.checkPathExist(localPath + filePath);
			if (FileUtil.checkFileExist(realPath) == 0) {
				FileUtil.deleteFile(realPath);
			}
			FileUtil.writeFileByCharsCode(realPath, data, 0);
			if (FileUtil.checkFileExist(realPath) == 0) {
				result.put("result", 1);
				//result.put("url", "/doc/" +record.getRecordTypeCode()+"/"+ fileName);
				result.put("url", new File(realPath).toURI().toURL().toString());
				//String filePathNmae=record.getRecordTypeCode()+"/"+record.getRecordId() + ".html";
				result.put("filePathName",docPath+filePath+fileName);
			} else {
				result.put("result", 0);
				result.put("errorText", "生成Html文件失败!");
			}
		} else {

			if (record.getType() == 0) {
				// ===================================================================
				// 病历
				// ===================================================================
				//先获取签名图片
				Map<String, Object> param =getSignMessage(recordId,outInSign);
				param.put("BLNR", record.getBlnr());
				param.put("realPath", localPath + filePath);
				param.put("fileName", fileName);
				param.put("creatHtml", "1");
				boolean i = new DataToHtml().BlobToHtmlView(param);
				if (i == true) {
					result.put("result", 1);
					//result.put("url", "/doc/" +record.getRecordTypeCode()+"/" + fileName);
					result.put("url", new File(realPath).toURI().toURL().toString());
					//String filePathNmae=record.getRecordTypeCode()+"/"+record.getRecordId() + ".html";
					result.put("filePathName",docPath+filePath+fileName);
				} else {
					result.put("result", 0);
					result.put("errorText", "生成Html文件失败!");
				}
			} else {
				// ===================================================================
				// 病程
				// ===================================================================
				// 获取页眉页脚
				RecordDomain head = new RecordDomain();
				if("1".equals(outInSign.toString())){
					head = clinicMedicationMapper.getClinicHead(Long.parseLong(record.getVisitId()));
					RecordDomain head2 = clinicRecordMapper.getClinicRecordDataById(head.getRecordId());
					if (head == null || head2 == null) {
						result.put("result", 0);
						result.put("errorText", "未查询到病程的页眉页脚!");
						return result;
					}

					head.setBlnr(head2.getBlnr());
				}else{
					head = recordMapper.getEmrHead(record.getVisitId());
					if (head == null) {
						result.put("result", 0);
						result.put("errorText", "未查询到病程的页眉页脚!");
						return result;
					}
				}

				
				filePath = record.getVisitId() + "/" + record.getRecordTypeCode() + "/";
				fileName = "" + head.getRecordId() + ".html";
				data = new String(head.getBlnr());
				realPath = localPath + filePath + fileName;
				String sHeader = "";
				String sFooter = "";
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("BLNR", head.getBlnr());
				param.put("realPath", localPath + filePath);
				param.put("fileName", fileName);
				param.put("creatHtml", "0");
				boolean i = new DataToHtml().BlobToHtmlView(param);
				if (i != true) {
					result.put("result", 0);
					result.put("errorText", "页眉转换HTML失败!");
					return result;
				} else {
					sHeader = (String) param.get("sHeader");
					sFooter = (String) param.get("sFooter");
				}

				// 获取病程记录
				List<RecordDomain> courseList = new ArrayList<RecordDomain>();
				if("1".equals(outInSign.toString())){
					courseList = clinicMedicationMapper.getClinicCourseList(Long.parseLong(record.getVisitId()));
				}else{
					courseList = recordMapper.getEmrCourseList(record.getVisitId());
				}
				if (courseList.size() == 0) {
					result.put("result", 0);
					result.put("errorText", "未查询到病程记录!");
					return result;
				}

				String strOut="";
				RecordDomain temp = new RecordDomain();
				for (RecordDomain detail : courseList) {
					Map<String, Object> courseParam =getSignMessage(detail.getRecordId(),outInSign);
					if("1".equals(outInSign.toString())) {
						temp = clinicRecordMapper.getClinicRecordDataById(detail.getRecordId());
						detail.setBlnr(temp.getBlnr());
					}
					courseParam.put("BLNR", detail.getBlnr());
					courseParam.put("realPath", localPath + filePath);
					courseParam.put("fileName", fileName);
					courseParam.put("creatHtml", "0");
					courseParam.put("isParkey", "1"); //病程标记，主要处理据左右问题
			        boolean ire = new DataToHtml().BlobToHtmlView(courseParam);
			        if (ire!=true){
			        	strOut = strOut + "病程编号"+detail.getRecordId()+"转HTML字符串失败";
			        }
			        else {
						String ss=(String)courseParam.get("html");
						sHeader = sHeader + ss;
			        }
				}
                if("".equals(strOut)){
    				// 生成HTML文件
					String sHTML = sHeader + sFooter;
					// 判断路径是否存在
					FileUtil.checkPathExist(localPath + filePath);
					FileUtil.writeFileByCharsCode(realPath, sHTML, 0);
					if (FileUtil.checkFileExist(realPath) == 0) {
						result.put("result", 1);
						//result.put("url", "/doc/"+record.getRecordTypeCode()+"/" +record.getVisitId()+"/" + fileName);
						result.put("url", new File(realPath).toURI().toURL().toString());
						//String filePathNmae=record.getRecordTypeCode()+"/"+record.getRecordId() + ".html";
						result.put("filePathName",docPath+filePath + fileName);
						return result;
					} else {
						result.put("result", 0);
						result.put("errorText", "生成HTML文件失败!");
						return result;
					}
                }else{
					result.put("result", 0);
					result.put("errorText", strOut);
					return result;
                }
			}
		}

		return result;
	}
	
	private Map<String, Object> getSignMessage(Long recordId,Long outInSign) {
		Map<String, Object> param = new HashMap<String, Object>();
		
		List<RecordSignDomain> signList = new ArrayList<RecordSignDomain>();

		if("1".equals(outInSign.toString())){
			signList = clinicMedicationMapper.getClinicSignList(recordId);
		}else{
			signList = recordMapper.getEmrSignList(recordId);
		}

		String signStrList = "";
		for (RecordSignDomain detail : signList) {
			String signRecordId = detail.getSignRecordId().toString();
			String signId = detail.getSignId().toString();
			byte[] signImage;
			if("1".equals(outInSign.toString())){
				//跨库 重新获取
				RecordSignDomain sign = recordMapper.getEmrSignFile(detail.getSignId());
				signImage = sign.getSignFile();
			}else{
				signImage = detail.getSignFile();
			}
			String key = signId + "#" + signRecordId;
			String skey = "," + key + ",";
			String sList = "," + signStrList + ",";
			if (!sList.contains(skey) && signImage != null) {
				param.put(key, signImage);
				if ("".equals(signStrList)) {
					signStrList = key;
				} else {
					signStrList = signStrList + "," + key;
				}
			}
		}
		if (!"".equals(signStrList)) {
			param.put("qmlist", signStrList);
		}
		return param;
	}
	public BaseResponse<List<HealthRecordsDomain>> getHealthRecordsList(HealthRecordsPojo pojo){
		BaseResponse<List<HealthRecordsDomain>>domainBaseResponse=new BaseResponse<>();
		String brid=null;
		if (pojo.getQueryType()==1){
			brid=pojo.getPatientId();
		}else{
			brid=publicService.getBRID(pojo.getOrganizationId(), pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
					pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
		}
		if (TextUtils.isEmpty(brid)){
			domainBaseResponse.setCode(Constant.successResponse);
			domainBaseResponse.setMessage("查询不到该病人信息");
			return domainBaseResponse;
		}
		if (pojo.getType()==1) {
			//门诊
			mzHealthRecords = clinicMedicationMapper.getMzHealthRecords(pojo.getOrganizationId(), brid);
			healthRecordsList=mzHealthRecords;
		}else if (pojo.getType()==2){
			zyHealthRecords = clinicMedicationMapper.getZyHealthRecords(pojo.getOrganizationId(), brid);
			healthRecordsList=zyHealthRecords;
		}else{
			healthRecordsList = new ArrayList<>();
			mzHealthRecords = clinicMedicationMapper.getMzHealthRecords(pojo.getOrganizationId(), brid);
			zyHealthRecords = clinicMedicationMapper.getZyHealthRecords(pojo.getOrganizationId(), brid);
			healthRecordsList.addAll(mzHealthRecords);
			healthRecordsList.addAll(zyHealthRecords);
		}
		if (healthRecordsList.size()==0){
			domainBaseResponse.setCode(Constant.successResponse);
			domainBaseResponse.setMessage("查询不到该病人就诊记录");
			return domainBaseResponse;
		}
		List<DoctorInfo> doctorInfoList=publicService.getDoctorInfo(pojo.getOrganizationId());
		List<KsdmDomain> ksdmDomainList=publicService.getKsdm(pojo.getOrganizationId());
		List<BrxzInfo> brxzInfoList=publicService.getBrxzList();
		List<HospitalInformation> supportJgmcList=cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);

		//获取科室信息、医生信息、病人性质
		for (HealthRecordsDomain healthRecordsDomain:healthRecordsList){
			for (DoctorInfo doctorInfo:doctorInfoList){
				if (doctorInfo.getYGDM().equals(healthRecordsDomain.getDoctorId())){
					healthRecordsDomain.setDoctorName(doctorInfo.getYGXM());
					break;
				}
			}
			for (KsdmDomain ksdmDomain:ksdmDomainList){
				if (ksdmDomain.getKSDM().equals(healthRecordsDomain.getDepartmenId())){
					healthRecordsDomain.setDepartmentName(ksdmDomain.getKSMC());
					break;
				}
			}
			for (BrxzInfo brxzInfo:brxzInfoList){
				if (brxzInfo.getBRXZ().equals(healthRecordsDomain.getBRXZ())){
					healthRecordsDomain.setPatientNature(brxzInfo.getXZMC());
					break;
				}
			}
			for (HospitalInformation hospitalInformation:supportJgmcList){
				if (hospitalInformation.getOrganizationId().equals(healthRecordsDomain.getOrganizationId())){
					healthRecordsDomain.setOrganizationName(hospitalInformation.getOrganizationName());
					break;
				}

			}

		}
		domainBaseResponse.setData(healthRecordsList);
		domainBaseResponse.setCode(Constant.successResponse);
		domainBaseResponse.setMessage("请求成功");
		return domainBaseResponse;
	}
}
